package com.solcoo.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.solcoo.dao.DingDanDao;
import com.solcoo.dao.RechargeDao;
import com.solcoo.dao.YongHuDao;
import com.solcoo.dao.ZhangHuDao;
import com.solcoo.dao.ZheKouDao;
import com.solcoo.pojo.DingDan;
import com.solcoo.pojo.RechargeInfo;
import com.solcoo.pojo.TempGrdd;
import com.solcoo.pojo.TempShdd;
import com.solcoo.pojo.TempYhAndDd;
import com.solcoo.pojo.YongHu;
import com.solcoo.pojo.ZhangHu;
import com.solcoo.service.DataService;
import com.solcoo.service.DingDanService;

@Controller
public class DingDanController extends AbstractController {
	
	@Resource
    private DingDanDao dingDanDao;
	@Resource
    private ZhangHuDao zhangHuDao;
    @Resource
    private YongHuDao yongHuDao;
    @Resource
    private ZheKouDao zheKouDao;
    @Resource
    private DingDanService dingDanService;
    @Resource
    private RechargeDao rechargeDao;
    @Resource
    private DataService dataService;
    
    private final static String REPORT_PATH = "static/pic/report/";
    private static Logger logger = Logger.getLogger(DingDanController.class);

    // 充值
    @RequestMapping(value="shRecharge.do")
    public @ResponseBody JsonResult shRecharge(DingDan dingdan,String shoujih) throws Exception {
    	return dingDanService.throwExcepshRecharge(dingdan,shoujih,"1");
    }

    // 充值2
    @RequestMapping(value="shRecharge2.do")
    public @ResponseBody JsonResult shRecharge2(DingDan dingdan,String shoujih,Long rechargeid) throws Exception {
    	if(rechargeid!=null && rechargeid>0) {
    		RechargeInfo ri = rechargeDao.getRechargeInfo(rechargeid);
        	if(ri == null) {
        		return this.getFailJsonResult("该活动已被删除，请获取最新活动！");
        	}
    	}
    	return dingDanService.throwExcepshRecharge(dingdan,shoujih,"1");
    }
    
    // 支付
    @RequestMapping(value="shPay.do")
    public @ResponseBody JsonResult shPay(DingDan dingdan,String shoujih) throws Exception {
    	return dingDanService.throwExcepshPay(dingdan,shoujih);
    }
    
    // 支付2，新验证码产生后
    @RequestMapping(value="shPay2.do")
    public @ResponseBody JsonResult shPay2(DingDan dingdan,String qrcode) throws Exception {
    	if("abcdefghij".indexOf(qrcode.substring(1,2)) > 0) {
    		String s = "abcdefghij";
        	String yonghum = "";
        	for(int i=0;i<5;i++) {
        		yonghum += s.indexOf(qrcode.substring(i*2+1, i*2+2));
        	}
        	YongHu yh = yongHuDao.selectUserByYonghum(yonghum);
    		String shoujih = yh.getShoujih();
    		return dingDanService.throwExcepshPay(dingdan,shoujih);
    	} else {
    		YongHu yh = yongHuDao.selectUserByPhone(qrcode);
    		if(yh.getQrcode()!=null && "1".equals(yh.getQrcode())) {
    			return this.getFailJsonResult("该二维码无效");
    		}
    		return dingDanService.throwExcepshPay(dingdan,qrcode);
    	}
    }

    // 商户查询订单
    @RequestMapping(value="shQueryDd.do")
    public @ResponseBody JsonResult shQueryDd(ZhangHu zh, String date, int youbiao) throws Exception {
        List<TempYhAndDd> dds;
        double zxiaofei = 0;
        double zchongzhi = 0;
        double zzengsong = 0;
        
        if(zh.getGerenid()>0) { // 商户查询单个客户账单
            List<DingDan> alldds = dingDanDao.queryAllList(zh.getShanghuid(),zh.getGerenid());
            if(alldds!=null && alldds.size()>0) {
                for(DingDan dd:alldds) {
                	// 总充值包括赠送的金额
                    if("1".equals(dd.getLeixing())) {
                        zchongzhi = new BigDecimal(zchongzhi).add(new BigDecimal(dd.getJine()).
                        		add(new BigDecimal(dd.getFreeAmount()))).doubleValue();
                        zzengsong = new BigDecimal(zzengsong).add(new BigDecimal(dd.getFreeAmount())).doubleValue();
                    } else if("2".equals(dd.getLeixing())) {
                        zxiaofei = new BigDecimal(zxiaofei).add(new BigDecimal(dd.getJine())).doubleValue();
                    }
                }
            }
            
            dds = dingDanDao.queryYDList(zh.getShanghuid(),zh.getGerenid(),youbiao);
            if(dds!=null && dds.size()>0) {
                youbiao = dds.get(dds.size()-1).getDingdan().getId();
            }
            List<TempYhAndDd> ddsa = dingDanDao.queryYDList(zh.getShanghuid(),zh.getGerenid(),youbiao);
            if(ddsa==null || ddsa.size()<=0) {
                youbiao = -1;
            }
        } else { // 客户查询所有客户账单
        	Date startDate = new Date();
        	if(date!=null && !"".equals(date)) {
        		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        		startDate = formatter.parse(date);
        	}
        	Date endDate = new Date(startDate.getTime() + 1000*3600*24);
        	Map<String, Object> param = new HashMap<String, Object>();
        	param.put("shanghuid", zh.getShanghuid());
        	param.put("startDate", startDate);
        	param.put("endDate", endDate);
        	if(youbiao > 0)
            	param.put("youbiao", youbiao);
        	
        	List<DingDan> alldds = dingDanDao.queryAllList(param);
            if(alldds!=null && alldds.size()>0) {
                for(DingDan dd:alldds) {
                	// 总充值（实收）不包括赠送的金额
                    if("1".equals(dd.getLeixing())) {
                        zchongzhi = new BigDecimal(zchongzhi).add(new BigDecimal(dd.getJine())).doubleValue();
                        zzengsong = new BigDecimal(zzengsong).add(new BigDecimal(dd.getFreeAmount())).doubleValue();
                    } else if("2".equals(dd.getLeixing())) {
                        zxiaofei = new BigDecimal(zxiaofei).add(new BigDecimal(dd.getJine())).doubleValue();
                    }
                }
            }

        	dds = dingDanDao.queryYDListByDate(param);
        	if(dds!=null && dds.size()>0) {
                youbiao = dds.get(dds.size()-1).getDingdan().getId();
            }
        	param.put("youbiao", youbiao);
            List<TempYhAndDd> ddsa = dingDanDao.queryYDListByDate(param);
            if(ddsa==null || ddsa.size()<=0) {
                youbiao = -1;
            }
        }
        
        TempShdd shdd = new TempShdd();
        shdd.setMyList(dds);
        shdd.setZchongzhi(zchongzhi);
        shdd.setZxiaofei(zxiaofei);
        shdd.setYoubiao(youbiao);
        shdd.setZzengsong(zzengsong);

        // 推送相关
        Integer grid = zh.getGerenid()==0?null:zh.getGerenid();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("shanghuid", zh.getShanghuid());
        param.put("gerenid", grid);
        param.put("shNQCount", 0);
    	zhangHuDao.updateNQCount(param);
    	dingDanDao.updateDDNQCount(param);
        
        return getSuccessJsonResult(shdd);
    }

    // 个人查询订单
    @RequestMapping(value="grQueryDd.do")
    public @ResponseBody JsonResult grQueryDd(ZhangHu zh, int youbiao) throws Exception {
        List<DingDan> myList = dingDanDao.queryList(zh.getShanghuid(),zh.getGerenid(),youbiao);
        if(myList.size() > 0)
            youbiao = myList.get(myList.size()-1).getId();
        List<DingDan> ddsa = dingDanDao.queryList(zh.getShanghuid(),zh.getGerenid(),youbiao);
        if(ddsa==null || ddsa.size()<=0) {
            youbiao = -1;
        }
        String shyhm = zh.getShanghuid() + "";
        while(shyhm.length() < 5) {
            shyhm = "0" + shyhm;
        }
        // 查询商户信息
        YongHu user = yongHuDao.selectUserByYonghum(shyhm);
        // 查询账户信息
        ZhangHu account = zhangHuDao.query(zh.getShanghuid(), zh.getGerenid());
        TempGrdd grdd = new TempGrdd();
        grdd.setMyList(myList);
        grdd.setYoubiao(youbiao);
        grdd.setUser(user);
        grdd.setAccount(account);

        // 推送相关
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("shanghuid", zh.getShanghuid());
        param.put("gerenid", zh.getGerenid());
        param.put("shNQCount", 0);
    	zhangHuDao.updateNQCount(param);
    	dingDanDao.updateDDNQCount(param);
        
        return getSuccessJsonResult(grdd);
    }

    // 商户增加经验值
    @RequestMapping(value="shAddJyz.do")
    public @ResponseBody JsonResult shAddJyz(int shanghuid,String shoujih,double jingyanz) throws Exception {
    	return dingDanService.throwExcepshAddJyz(shanghuid,shoujih,jingyanz);
    }

    // 商户删除订单
    @RequestMapping(value="deleteOrder.do")
    public @ResponseBody JsonResult deleteOrder(int id, String employeeid) throws Exception {
    	return dingDanService.throwExcepdeleteOrder(id, employeeid);
    }

    @RequestMapping(value="queryOrder.jspDo")
    public ModelAndView getAccountList(String merchantId, String startDateStr, String endDateStr, String empname, HttpServletRequest request) throws Exception {
    	String picPath = request.getSession().getServletContext().getRealPath(REPORT_PATH) + "/data/";

    	dataService.createSsksByDay30(picPath, Long.parseLong(merchantId)); // 近 30 天日实收款折线图
    	ModelAndView view = new ModelAndView();
        
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sf3 = new SimpleDateFormat("yyyy-MM-dd");
            
            Map<String, Object> param = new HashMap<String, Object>();
            
            Date startDate = null;
            Date endDate = null;
            
            if(merchantId != null && !"".equals(merchantId)) {
            	if ((startDateStr == null || "".equals(startDateStr)) && (endDateStr == null || "".equals(endDateStr))) {
            		String nowDate = sf3.format(new Date());
            		
            		startDateStr = nowDate;
            		endDateStr = nowDate;
            	}
            	
                if (startDateStr != null && !"".equals(startDateStr)) {
                    startDateStr += " 00:00:00";
                    startDate = sf.parse(startDateStr);
                	param.put("startDate", startDate);
                }
                
                if (endDateStr != null && !"".equals(endDateStr)) {
                    endDateStr += " 23:59:59";
                    endDate = sf.parse(endDateStr);
                	param.put("endDate", endDate);
                }
                
                param.put("shanghuid", Integer.valueOf(merchantId));
                param.put("empname", empname);
                
                List<DingDan> orders = dingDanService.getOrderList(param);
                
                BigDecimal inTotal = BigDecimal.ZERO;
                BigDecimal outTotal = BigDecimal.ZERO;
                BigDecimal realInAmountTotal = BigDecimal.ZERO;
                
                if (orders != null) {
                    for (DingDan order : orders) {
                    	// 充值
                        if ("1".equals(order.getLeixing())) {
                            double realAmount = BigDecimal.valueOf(order.getJine()).add(BigDecimal.valueOf(order.getFreeAmount())).doubleValue();
                            order.setRealInAmount(realAmount);
                            realInAmountTotal = realInAmountTotal.add(BigDecimal.valueOf(realAmount));
                            inTotal = inTotal.add(BigDecimal.valueOf(order.getJine()));
                        }
                        // 支付
                        else if ("2".equals(order.getLeixing())) {
                            outTotal = outTotal.add(BigDecimal.valueOf(order.getJine()));
                        }
                    }
                }
                
                view.addObject("orders", orders);
                view.addObject("inTotal", inTotal);
                view.addObject("outTotal", outTotal);
                view.addObject("realInAmountTotal", realInAmountTotal);
                view.addObject("shanghuid", merchantId);
                view.addObject("empname", empname);
                
                if (startDate != null) {
                    view.addObject("startDateStr", sf3.format(startDate));
                }
                
                if (endDate != null) {
                    view.addObject("endDateStr",sf3.format(endDate));
                }
                
                view.setViewName("orderInfos");
            }
            else {
                view.setViewName("orderInfos");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception(e);
        }
        return view;
    }

    /**
     * 用户获取月订单流水
     */
    @RequestMapping(value = "monthStream.do")
    public @ResponseBody Map<String, Object> monthStream(int gerenid, String year, String updateMonth) throws Exception {
    	return dingDanService.getMonthStream(gerenid, year, updateMonth);
    }
    
    /**
     * 用户获取日订单流水
     */
    @RequestMapping(value = "dayStream.do")
    public @ResponseBody Map<String, Object> dayStream(int gerenid, String year, String month, String updateDay) throws Exception {
    	return dingDanService.getDayStream(gerenid, year, month, updateDay);
    }
    
    /**
     * 获取订单流水
     */
    @RequestMapping(value = "stream.do")
    public @ResponseBody Map<String, Object> stream(int gerenid, String date) throws Exception {
    	return dingDanService.getStream(gerenid, date);
    }
    
    /**
     * 获取商家支出报表
     */
    @RequestMapping(value = "reportByMerchant.do")
    public @ResponseBody Map<String, Object> reportByMerchant(int gerenid, String yearAndMonth) throws Exception {
    	return dingDanService.getReportByMerchant(gerenid, yearAndMonth);
    }
    
    /**
     * 获取商家支出报表明细
     */
    @RequestMapping(value = "reportmxByMerchant.do")
    public @ResponseBody Map<String, Object> reportmxByMerchant(int gerenid, String yearAndMonth, String shanghuid, String updateDay) throws Exception {
    	return dingDanService.getReportmxByMerchant(gerenid, yearAndMonth, shanghuid, updateDay);
    }
    
    /**
     * 获取类型支出报表
     */
    @RequestMapping(value = "reportByMerchantType.do")
    public @ResponseBody Map<String, Object> reportByMerchantType(int gerenid, String yearAndMonth) throws Exception {
    	return dingDanService.getReportByMerchantType(gerenid, yearAndMonth);
    }
    
    /**
     * 获取类型支出报表明细
     */
    @RequestMapping(value = "reportmxByMerchantType.do")
    public @ResponseBody Map<String, Object> reportmxByMerchantType(int gerenid, String yearAndMonth, Long merchantTypeid, String updateDay) throws Exception {
    	return dingDanService.getReportmxByMerchantType(gerenid, yearAndMonth, merchantTypeid, updateDay);
    }
    
    /**
     * 获取商户报表
     */
    @RequestMapping(value = "report.do")
    public @ResponseBody Map<String, Object> report(int gerenid, String date) throws Exception {
    	return dingDanService.getReport(gerenid, date);
    }
    
    /**
     * 获取商户类型报表
     */
    @RequestMapping(value = "reportByType.do")
    public @ResponseBody Map<String, Object> reportByType(int gerenid, String date) throws Exception {
    	return dingDanService.getReportByType(gerenid, date);
    }

    /**
	 * 获取月节省金额
	 */
    @RequestMapping(value = "mSaveMoney.do")
    public @ResponseBody Map<String, Object> mSaveMoney(int gerenid, String ym) throws Exception {
    	return dingDanService.getMSaveMoney(gerenid, ym);
    }
    
}
